<?php

namespace app\api\controller;

use app\api\model\TieBa AS TieModel;
use app\api\model\Oauth;
use app\api\model\TieBaFile;
use app\api\validate\Page;
use app\common\service\File;
use app\common\service\Mts;
use think\facade\Log;
use AppleSignIn\ASDecoder;
use app\api\service\WechatAuth;
use think\facade\Env;

class TieBa extends Base
{


    /**
     * 贴吧帖子列表 | 用户个人主页帖子列表
     * @return array
     * @throws \think\Exception\DbException
     */
    public function index()
    {
        $page = $data['page'] = input('page') ? input('page') : 1;
        $size = $data['size'] = input('size') ? input('size') : $this->pageSize;
        $uid = input('uid') ? input('uid') : 0;
        $typeId = input('typeId') ? input('typeId') : 0;

        // 检测变量
        $validate = new Page();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        $oauthId = $this->oauthInfo['id'];

        $user = [];
        // 存在uid，则获取个人用户主页的帖子列表
        if ($uid > 0) {
            $user = Oauth::getOne($uid);
            if (empty($user)) {
                return self::sendResult(110);
            }
        }
        $model = TieModel::getList($oauthId, $typeId, $page, $size, $user);
        return self::sendResult(self::$okCode, $model);
    }

    /**
     * 帖子详情
     * @param $tieId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read($tieId)
    {
        $page = $data['page'] = input('page') ? input('page') : 1;
        $size = $data['size'] = input('size') ? input('size') : $this->pageSize;
        $commentId = input('commentId') ? input('commentId') : 0;

        if ($tieId <= 0) {
            return self::sendResult(100);
        }

        // 检测变量
        $validate = new Page();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        $oauthId = $this->oauthInfo['id'];
        $model = TieModel::getOne($tieId, $oauthId, $commentId, $page, $size);
        return self::sendResult(self::$okCode, $model);
    }

    /**
     * 发布帖子
     * @return array
     * @throws \Exception
     */
    public function create()
    {
        // 帖子类型
        $typeId = $data['typeId'] = input('typeId');
        $content = $data['content'] = input('content');
        $isDraft = $data['isDraft'] = input('isDraft');
        $files = input('files');

        $config = config('wx_mini');
        $auth = new WechatAuth($config['app_id'],$config['app_secret']);
        $auth->getAccessToken("client",null);
        //检测文本是否合法
        $dat = $auth->checkContentSecure($content);
        if($dat['errcode'] != 0){
            return self::sendResult(102, [], '内容含有含有敏感信息，请检测后重新发送');
        }


        // 检测变量
        $validate = new \app\api\validate\TieBa();
        if (!$validate->check($data)) {
            return self::sendResult(102, [], $validate->getError());
        }

        if (!empty($files)) {
            if (!is_string($files) || empty($files = json_decode($files, true)) || !is_array($files)) {
                return self::sendResult(102, [], '文件数据错误');
            }

            if (count($files) > 10) {
                return self::sendResult(133);
            }

            // 计算类型对应的能上传文件的个数
            $typeCount = array_count_values(array_column($files, 'type'));
            if (isset($typeCount[TieBaFile::TYPE_IMG]) && $typeCount[TieBaFile::TYPE_IMG] > 9) {
                return self::sendResult(134);
            }

            if (isset($typeCount[TieBaFile::TYPE_VIDEO]) && $typeCount[TieBaFile::TYPE_VIDEO] > 1) {
                return self::sendResult(135);
            }
        }

        $oauthId = $this->oauthInfo['id'];
        $model = TieModel::addOne($oauthId, $typeId, $content, $isDraft, $files);
        if ($model) {
            $code = self::$okCode;
            $msg = $isDraft == TieModel::DRAFT ? '已保存至草稿' : '已经将帖子提交到后台管理审核，审核通过后将会展示在贴吧';
        } else {
            $code = 117;
            $msg = '发帖失败，请稍后再试';
        }

        return self::sendResult($code, $model, $msg);
    }

    /**
     * 删除自己的帖子
     * @param $tieId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delete($tieId)
    {
        if ($tieId <= 0) {
            return self::sendResult(102);
        }

        $oauthId = $this->oauthInfo['id'];

        $tie = TieModel::getOneById($tieId);
        if (empty($tie)) {
            return self::sendResult(118);
        }

        if ($tie['uid'] != $oauthId) {
            return self::sendResult(119);
        }

        TieModel::deleteOne($tieId, $oauthId);
        return self::sendResult(self::$okCode, [], '删除成功');
    }

    // 上传文件
    public function upload()
    {
        // 文件类型，1图片，2视频
        $type = input('type');
        if (empty($type)) {
            return self::sendResult(100);
        }

        $typeArr = TieBaFile::attributes('type');
        if (!isset($typeArr[$type])) {
            return self::sendResult(102);
        }

        // 保存文件名字和路径
        if ($type == TieBaFile::TYPE_IMG) {
            $dir = 'tie/img';
            $size = TieBaFile::SIZE_IMG;
        } else {
            $dir = 'tie/video';
            $size = TieBaFile::SIZE_VIDEO;
        }

        $file = new File($size);
        $return = $file->formFile($dir, $type);
        
        
        return self::sendResult($return['code'], $return['data'], $return['msg']);
    }

    public function test(){
        
        var_dump(Env::get('ROOT_PATH'));
        
    }

    
}